package websocketgulu.demo.websocket;

import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.ByteBuffer;

@ServerEndpoint(value = "/api/connws", configurator = GetHttpSessionConfigurator.class)
/*
ServerEndpointer注解表示的是，这个类是一个websocket服务器，
value表示的是它所绑定的url
 */
@Component
public class showDiagramWebSocket {
    private static Session session;
    private HttpSession httpSession;

    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        this.session = session;

        HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        this.httpSession = httpSession;
        System.out.println("someone connected!");
        /*try {
            //this.session.getBasicRemote().sendText("have connected to gulu backEnd");
        } catch (IOException e) {
            e.printStackTrace();
        }*/
    }

    @OnMessage
    public void onMessage(String message, Session session) {

        /*this.jedis = jedisUtils.getJedis();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        String key = dateFormat.format(calendar.getTime());

        String lpop = jedis.lpop(key);
        while (lpop != null) {
            try {
                this.session.getBasicRemote().sendText(lpop);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(lpop);
            lpop = jedis.lpop(key);
        }*/
        System.out.println(message);
    }

    @OnClose
    public void onClose(Session session){
        /*this.jedis.close();*/
    }

    public static void sendMessage(String msg) {
        try {
            if (session.isOpen()) {
                synchronized(session){
                    System.out.println("w:"+msg);
                    session.getBasicRemote().sendText(msg);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static boolean serviceOn() {
        if (null != session) {
            return true;
        } else {
            return false;
        }
    }

    public static void sendBinary(ByteBuffer bf) {
        try {
            if (session.isOpen()) {
                synchronized(session){
                    session.getBasicRemote().sendBinary(bf);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static ByteBuffer encodeValue(byte[] value) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(value.length);
        byteBuffer.clear();
        byteBuffer.get(value, 0, value.length);
        return byteBuffer;
    }
}
